#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/21 18:49
# @Author : 闫峰
# @File    : pop_choice_products_list_syc_bei.py
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/20 13:46
# @Author : 闫峰
# @File    : test_monitor_inf_listing.py
import requests
from retrying import retry

from common.setting import ensure_path_sep
from third_services.aliexpress.utils import ErpDesUtil
from utils.mysqlUtils.db_pool import Database
from utils.logging_tool.init_logger import init_logger
from utils.times_tool.time_control import count_time
from utils.otherutils.MyThreadPool import MyThreadPool

INFO, ERROR, WARNING = init_logger()


class Test:
    znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")

    def find_listing(self, source_id,UserTokenSecretAccessKey):
        expect_set = self.get_expect_listing_set(source_id,UserTokenSecretAccessKey)
        actual_set = self.get_actual_listing_set(source_id)
        if expect_set != actual_set:
            source_sku_deletion_set = expect_set-actual_set
            source_sku_more_set = actual_set-expect_set
            db_java_test = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
            insert_sql = """
            REPLACE INTO test_zhcxkj_center_datasync_comprehensive.m_aliexpress_listing_pop_choice_product_monitor 
            (source_id, source_sku_more_set,source_sku_deletion_set,create_time,update_time,delete_count,more_count)
            VALUES (%s,%s,%s,now(),now(),%s,%s);
            """
            db_java_test.execute(insert_sql, (source_id, str(source_sku_more_set), str(source_sku_deletion_set),str(len(source_sku_deletion_set)),str(len(source_sku_more_set))))
    @count_time
    def get_expect_listing_set(self,source_id,UserTokenSecretAccessKey):
        current_page = 1
        expect_set = set()
        auth = ErpDesUtil.desEncode(UserTokenSecretAccessKey)
        while True:
            total_page,pop_choice_product = self.api_(auth,current_page,source_id)
            pop_choice_product_set = set(map(lambda x:x['product_id'],pop_choice_product))
            expect_set |= pop_choice_product_set

            if current_page == total_page:
                break
            current_page += 1
        return expect_set
    def get_actual_listing_set(self,source_id):
        get_actual_set = """
        				 select a.ProductId
        				 from m_aliexpress_listing_pop_choice_product a
        				 JOIN m_aliexpress_listing_sub b on a.CustomerId=b.CustomerId AND a.OrderSourceId=b.OrderSourceId AND a.ProductId=b.ProductId
        				 WHERE a.CustomerId=1
        				 AND a.OrderSourceId=%s
        				 and b.EditStatus !=3
                """
        actual_list = self.znkd_db.fetch_all_tuple(get_actual_set, (source_id,))
        actual_set = set(map(lambda x: x[0], actual_list))
        return actual_set
    @retry(stop_max_attempt_number=5, wait_fixed=2000)
    def api_(self,UserTokenSecretAccessKey,current_page,source_id):
        print(f"source_id={source_id} current_page={current_page}")
        url = f"""https://erpapi.zhcxkj.com/Erp/AliExpressApi/PopChoiceProductsList"""
        headers = {
            "Authorization": "Basic YXBpdXNlcjpFN0kxLWxJX2QjOGRscw=="
        }
        data = {
            "input": {
                "param": {
                    "product_id": None,
                    "joined_product_tab": "joined",
                    "current_page":current_page,
                    "page_size":50
                }
            },
            "UserTokenSecretAccessKey": UserTokenSecretAccessKey
        }
        res = requests.post(url=url,headers=headers,json=data)
        if res.status_code == 200:
            total_page = res.json()['data']['aliexpress_pop_choice_products_list_response']["result"]['total_page']
            pop_choice_product = \
            res.json()['data']['aliexpress_pop_choice_products_list_response']["result"]['pop_choice_product_list'][
                'pop_choice_product']
            return total_page,pop_choice_product
        else:
            raise Exception("status_code!=200")

    def test__(self):
        """
        得到 t_walmart_listing在线的数据 涉及禁售 律所 仿牌
        :return:
        """
        self.delete_tables()
        OrderSourceIdUserTokenSecretAccessKey_list = self.get_task_list()
        # 线程池执行
        MyThreadPool(10).multithreaded(self.find_listing, OrderSourceIdUserTokenSecretAccessKey_list)



        # db_java_test = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        # # 得到本都数据表 m_aliexpress_listing_pop_choice_product_monitor
        # get_actual_list = """
        # SELECT source_id,delete_count,more_count
        # FROM test_zhcxkj_center_datasync_comprehensive.m_aliexpress_listing_pop_choice_product_monitor
        # """
        # actual_list = db_java_test.fetch_all_tuple(get_actual_list, ())
        # actual_list = sorted(actual_list, key=lambda x: int(x[1]), reverse=True)
        # actual_list_split = actual_list[0:9]
        # source_id_num = len(actual_list)
        # source_sku_num = 0
        # for source_id,delete_count,more_count in actual_list:
        #     source_sku_num += int(delete_count)
        # text = f"---  \n\n" \
        #        f"店铺数：<font color='red' size='5'>{source_id_num}</font>  本地缺少产品数：<font color='red' size='5'>{source_sku_num}</font>\n\n" \
        #        f"---  \n\n" \
        #        f"详细渠道sku查询数据库 m_aliexpress_listing_pop_choice_product_monitor  \n\n" \
        #        f"---  \n\n"
        # for source_id,delete_count,more_count in actual_list_split:
        #     text += f"渠道id:<font color='red' size='5'>{source_id}</font>  本地缺少产品数<font color='red' size='5'>{delete_count}</font>个   \n\n" \
        #             f"---  \n\n"
        # DingTalkSendMsg(DingTalk='all_platform_monitor').send_success(text=text,
        #                                                               title='速卖通POP产品同步及时性监控服务【测试组】',
        #                                                               phone_list=[18118758151, 15767667648,
        #                                                                           13841609957])
        print("执行完成")


    def delete_tables(self):
        # 清除表
        db_java_test = Database(ensure_path_sep("\\config\\shopeev2_config.yaml.bak"), "test_jdw_database")
        delete_sql = """
        delete from test_zhcxkj_center_datasync_comprehensive.m_aliexpress_listing_pop_choice_product_monitor
        """
        db_java_test.execute(delete_sql,())


    def get_task_list(self):
        getOrderSourceIdUserTokenSecretAccessKey_list = """
        select a.OrderSourceId,b.UserTokenSecretAccessKey
        from sys_ordersource a
        left join sys_ordersource_authorization b on a.CustomerId=b.CustomerId and a.OrderSourceId=b.OrderSourceId
        where a.OrderSourceType=57
        and a.IsActive=1
        and a.IsDelete=0
        and a.CustomerId =1
        and b.IsActive=1
        # and a.OrderSourceId=5159
        """
        OrderSourceIdUserTokenSecretAccessKey_list = self.znkd_db.fetch_all_tuple(
            getOrderSourceIdUserTokenSecretAccessKey_list, ())
        return OrderSourceIdUserTokenSecretAccessKey_list


if __name__ == '__main__':
    Test().test__()
